﻿using AutoMachine;
using CommonTool;
using Motions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Tool;
using static CommonTool.SystemMgr;

namespace Station
{
    abstract class StationBase
    {

        /// <summary>
        /// 流程名称
        /// </summary>
        private string StationName = string.Empty;

        /// <summary>
        /// 流程线程
        /// </summary>
        private Thread m_thread = (Thread)null;
        public long StartTime = 0;
        public bool TestBool = false;
        //线程是否运行中
        private bool m_bRunThread;

        public StationBase(string name)
        {
            this.StationName = name;//流程名称      
        }

        /// <summary>
        /// 启动线程
        /// </summary>
        public void StartRun()
        {
            GlobalVar.LCRTCP.DataReceivedEvent += LCRTCP_DataReceivedEvent;
            m_thread = (Thread)null;
            if (this.m_thread == null)
            {
                this.m_thread = new Thread(new ThreadStart(this.Running));
            }
            if (this.m_thread.ThreadState != 0)
            {
                this.m_bRunThread = true;
                this.m_thread.IsBackground = true;
                this.m_thread.Start();
            }
        }

        /// <summary>
        /// 停止线程
        /// </summary>
        public void StopRun()
        {
            Thread.Sleep(50);
            StopWork();
            if (this.m_thread == null)
            {
                return;
            }
            this.m_bRunThread = false;
            if (!this.m_thread.Join(5000))
            {
                this.m_thread.Abort();
            }
            this.m_thread = (Thread)null;
        }

        /// <summary>
        /// 自动流程
        /// </summary>
        public void Running()
        {
            while (this.m_bRunThread == true)
            {
                if (Device.StateMode != Device.STATEMode.RUN)
                {
                    Thread.Sleep(10);
                }
                else
                {
                    {
                        AutoWork();
                    }
                    Thread.Sleep(5);

                }
            }
        }

        /// <summary>
        /// 自动流程步
        /// </summary>
        public abstract void AutoWork();

        /// <summary>
        /// 停止流程步
        /// </summary>
        public abstract void StopWork();

        /// <summary>
        /// 急停流程步
        /// </summary>
        public abstract void EmgWork();

        /// <summary>
        /// 绝对定位
        /// </summary>
        /// <param name="PointName"></param>
        public void AbsMove(string PointName, double offset = 0)
        {
            int nAxisNo = SystemCfg.Po(StationName)[PointName].AxisNo;//轴号
            double Speed = SystemCfg.Po(StationName)[PointName].Speed;//速度 
            double Pos = SystemCfg.Po(StationName)[PointName].Point + offset;//目标位置    
            //绝对定位

            MotionMgr.GetInstance().AbsMove(nAxisNo, Pos, Speed);
            Thread.Sleep(10);
        }

        /// <summary>
        /// 等待轴到位
        /// </summary>
        /// <param name="PointName"></param>
        public void WaitAbs(string PointName, double offset = 0)
        {
            int nAxisNo = SystemCfg.Po(StationName)[PointName].AxisNo;//轴号
            double Speed = SystemCfg.Po(StationName)[PointName].Speed;//速度 
            double Pos = SystemCfg.Po(StationName)[PointName].Point + offset;//目标位置    
            //等待轴到位
            MotionMgr.GetInstance().WaitAbs(nAxisNo, Pos);
            LogView.GetInstance().ShowLog(LogView.LogType.Oper, PointName + "到位,Offset=" + offset.ToString());
        }

        #region IO操作
        /// <summary>
        /// IO输出
        /// </summary>
        /// <param name="name"></param>
        /// <param name="Bit"></param>
        public void WriteOut(string name, bool Bit)
        {
            MotionMgr.GetInstance().WriteOut(name, Bit);
        }

        /// <summary>
        /// 等待输入信号
        /// </summary>
        /// <param name="name"></param>
        /// <param name="bit"></param>
        public void WaitIn(string name, bool bit)
        {
            MotionMgr.GetInstance().WaitIn(name, bit);
        }

        /// <summary>
        /// 等到输出信号
        /// </summary>
        /// <param name="name"></param>
        /// <param name="bit"></param>
        public void WaitOut(string name, bool bit)
        {
            MotionMgr.GetInstance().WaitOut(name, bit);
        }
        /// <summary>
        /// 读取输入
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool ReadIn(string name)
        {
            return MotionMgr.GetInstance().ReadIn(name);
        }
        /// <summary>
        /// 读取输出
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool ReadOut(string name)
        {
            return MotionMgr.GetInstance().ReadOut(name);
        }

        #endregion
        /// <summary>
        /// 延时时间
        /// </summary>
        /// <param name="milliSecond"></param>
        public void WaitDelay(int milliSecond)
        {
            int start = Environment.TickCount;
            while (Math.Abs(Environment.TickCount - start) < milliSecond)
            {
                Application.DoEvents();
            }
        }


        /// <summary>
        /// 单步模式
        /// </summary>
        public void WaitRun()
        {
            if (GlobalVar.OneStep == true)//单步模式
            {
                while (true)
                {
                    Thread.Sleep(10);
                    if (MotionMgr.GetInstance().ReadIn("启动1") || MotionMgr.GetInstance().ReadIn("启动"))
                    {
                        break;
                    }
                }
            }
            else
            {
                while (true)
                {
                    Thread.Sleep(10);
                    if (Device.StateMode == Device.STATEMode.RUN)
                    {
                        break;
                    }
                }
            }
        }
        decimal CP;
        decimal RP;
        /// <summary>
        /// 视觉数据接收
        /// </summary>
        /// <param name="str"></param>
        void LCRTCP_DataReceivedEvent(string str)
        {

            string[] str1 = str.Split(',');
            if (str1.Length == 3)
            {
                string CPstr = str1[0];
                string RPstr = str1[1];
                CPstr = CPstr.Split('E')[0];
                RPstr = RPstr.Split('E')[0];
                CP = decimal.Parse(CPstr) * 10;
                RP = decimal.Parse(RPstr) / 10;
                TestBool = true;
                //LogView.GetInstance().ShowLog(LogView.LogType.Oper, "网口接收:" + $"CP={CP}pF,RP={RP}");
            }

            //GlobalVar.DataCCD.Add(str);



        }

        public void BubbleSort(ref List<Tuple<double, double, double>> a)
        {
            for (int i = 0; i < a.Count; i++)
            {
                for (int j = 0; j < a.Count - 1 - i; j++)
                {
                    if (a[j].Item1 > a[j + 1].Item1)
                    {
                        Tuple<double, double, double> temp = a[j];
                        a[j] = a[j + 1];
                        a[j + 1] = temp;
                    }
                }

            }
            for (int i = 0; i < a.Count; i++)
            {
                for (int j = 0; j < a.Count - 1 - i; j++)
                {
                    if (a[j].Item2 > a[j + 1].Item2)
                    {
                        Tuple<double, double, double> temp = a[j];
                        a[j] = a[j + 1];
                        a[j + 1] = temp;
                    }
                }

            }
        }

        /// <summary>
        /// 等待指定位寄存器有效
        /// </summary>
        /// <param name="nIndex"></param>
        /// <param name="bit"></param>
        public void WaitSysBit(SysBit nIndex, bool bit)
        {
            SystemMgr.GetInstance().WaitSysBit(nIndex, bit);
        }

        /// <summary>
        /// 等待指定整形寄存器值有效
        /// </summary>
        /// <param name="nIndex"></param>
        /// <param name="num"></param>
        public void WaitSysInt(SysInt nIndex, int num)
        {
            SystemMgr.GetInstance().WaitSysInt((int)nIndex, num);
        }

        /// <summary>
        /// 等待指定浮点型寄存器值有效
        /// </summary>
        /// <param name="nIndex"></param>
        /// <param name="num"></param>
        public void WaitSysDouble(SysDouble nIndex, int num)
        {
            SystemMgr.GetInstance().WaitSysDouble((int)nIndex, num);
        }

        /// <summary>
        /// 向指定的位写值
        /// </summary>
        /// <param name="nIndex"></param>
        /// <param name="bBit"></param>
        public void WriteSysBit(SysBit nIndex, bool bBit)
        {
            SystemMgr.GetInstance().WriteSysBit(nIndex, bBit);
        }

        /// <summary>
        /// 向指定的Int写值
        /// </summary>
        /// <param name="nIndex"></param>
        /// <param name="nData"></param>
        public void WriteSysInt(SysInt nIndex, int nData)
        {
            SystemMgr.GetInstance().WriteSysInt(nIndex, nData);
        }

        /// <summary>
        /// 向指定的Double写值
        /// </summary>
        /// <param name="nIndex"></param>
        /// <param name="fdata"></param>
        public void WriteSysDouble(SysDouble nIndex, double fdata)
        {
            SystemMgr.GetInstance().WriteSysDouble((int)nIndex, fdata);
        }

        /// <summary>
        /// 获取指定的位寄存器状态
        /// </summary>
        /// <param name="nIndex"></param>
        /// <returns></returns>
        public bool GetSysBit(SysBit nIndex)
        {
            return SystemMgr.GetInstance().GetSysBit(nIndex);
        }

        /// <summary>
        /// 获取指定的整形寄存器的值
        /// </summary>
        /// <param name="nIndex"></param>
        /// <returns></returns>
        public int GetSysInt(SysInt nIndex)
        {
            return SystemMgr.GetInstance().GetSysInt((int)nIndex);
        }

        /// <summary>
        /// 获取指定的浮点型寄存器的值
        /// </summary>
        /// <param name="nIndex"></param>
        /// <returns></returns>
        public double GetSysDouble(SysDouble nIndex)
        {
            return SystemMgr.GetInstance().GetSysDouble((int)nIndex);
        }

        public void ShowLog(string Text)
        {
            LogView.GetInstance().ShowLog(LogView.LogType.Oper, Text);
        }

        /// <summary>
        /// 报警暂停，false会继续等待，true会跳过报错
        /// </summary>
        public bool PausedAlarm(string msg)
        {
            DateTime now = DateTime.Now;
            while (true)
            {
                LogView.GetInstance().ShowLog(LogView.LogType.Error, msg);
                GlobalVar.Buzzer = true;//蜂鸣器
                DialogResult result = MessageBox.Show(msg, "报警暂停", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);//最后一个改变默认焦点
                if (result == DialogResult.Abort)
                {
                    if (Device.StateMode == Device.STATEMode.Resetting)
                    {
                        Device.ChangeStateMode(Device.STATEMode.STOP);//切换暂停
                        return false;
                    }
                    if (Device.StateMode == Device.STATEMode.RUN)
                    {
                        Device.ChangeStateMode(Device.STATEMode.PAUSE);//切换暂停
                        return false;
                    }
                    GlobalVar.Buzzer = false;
                    return false;
                }
                else if (result == DialogResult.Retry)
                {
                    GlobalVar.Buzzer = false;
                    //重试
                    return false;
                }
                else if (result == DialogResult.Ignore)
                {
                    GlobalVar.Buzzer = false;
                    //忽略
                    return true;
                }
                Thread.Sleep(5);
            }
        }

        /// <summary>
        /// 报警暂停，false会继续等待，true会跳过报错
        /// </summary>
        public void Pause()
        {

            if (Device.StateMode == Device.STATEMode.RUN)
            {
                Device.ChangeStateMode(Device.STATEMode.PAUSE);//切换暂停

            }

        }

    }
}
